<template>
  <el-calendar v-model="value">
    <!-- 自定义日历的单元格 -->
    <template #date-cell="{ data }">
      <div class="calendar-day" @click="openDialog(data.day)">
        <!-- 日期数字 -->
        <div>{{ data.day.split('-')[2] }}</div>
        <!-- 这里显示事件数据 -->
        <ul>
          <li
              v-for="(item, index) in getEvents(data.day).slice(0,2)"
              :key="index"
              class="event-item"
              :class="item.type"
          >
            {{ item.courseName }}
          </li>
        </ul>
        <div v-if="getEvents(data.day).length > 2" class="more">+更多</div>
      </div>
    </template>
  </el-calendar>
  <el-dialog v-model="dialogVisible" title="课程详情" width="500px">
    <el-table :data="dialogCourses" border>
      <el-table-column prop="courseName" label="课程名称" />
      <el-table-column prop="coachName" label="教练" />
      <el-table-column prop="roomName" label="教室" />
      <el-table-column prop="schedule" label="时间" />
    </el-table>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import api from "@/util/api.js";

onMounted(() => {
  getCourse()
})

const value = ref(new Date())
const events = ref({})

const dialogVisible = ref(false)
const dialogCourses = ref([])

const getCourse = async () => {
  let resp = await api({
    url: "/course/all",
    method: "get",
  });
  const grouped = {}
  resp.data.forEach(course => {
    const day = course.schedule.split(' ')[0]
    if (!grouped[day]) {
      grouped[day] = []
    }
    grouped[day].push(course)
  })
  //排序
  for (const day in grouped){
    grouped[day].sort((a,b)=>new Date(a.schedule)-new Date(b.schedule))
  }
  events.value = grouped
  console.log(events.value)
}
// 根据日期获取当天的事件
const getEvents = (day) => {
  return events.value[day] || []
}
//弹窗
function openDialog(day) {
  dialogCourses.value = getEvents(day)
  if (dialogCourses.value.length>0){
    dialogVisible.value = true
  }
}

</script>

<style scoped>
.calendar-day {
  padding: 4px;
  font-size: 12px;
  cursor: pointer;
}
.date-num {
  font-weight: bold;
  margin-bottom: 2px;
}
.event-item {
  border-radius: 4px;
  margin-top: 2px;
  padding: 2px 4px;
  font-size: 10px;
  color: white;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.event-item.初级 {
  background: #9ea39c;
}
.event-item.中级 {
  background: #E6A23C; /* 橙色 */
}
.event-item.高级 {
  background: #F56C6C; /* 红色 */
}
.more {
  font-size: 10px;
  color: #909399;
  margin-top: 2px;
}
</style>
